package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.TingShuException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Component
@Aspect
public class UserLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(userLogin)")
    public Object login(ProceedingJoinPoint joinPoint,UserLogin userLogin) throws Throwable{
        //获取请求对象属性
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //转换为ServletRequestAttributes
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        //获取request
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //获取请求头里的token
        String token = request.getHeader("token");
        //构建key
        String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        //获取用户
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(loginKey);
        if(userLogin.required() && userInfoVo == null){
            throw new TingShuException(ResultCodeEnum.LOGIN_AUTH);
        }
        //用户登录，保存到AuthContextHolder
        if(userInfoVo != null){
            AuthContextHolder.setUserId(userInfoVo.getId());
            AuthContextHolder.setUsername(userInfoVo.getNickname());
        }
        //执行方法
        Object proceed = joinPoint.proceed();
        //清除AuthContextHolder的内容
        AuthContextHolder.removeUserId();
        return proceed;

    }
}
